package com.wyp168.leetcode;

import java.util.*;

/**
 * @ClassName CombinationSumSolution
 * @Title TODO leetcode 39 组合总和【难度登记：middle】
 * @Description TODO
 * @Author wyp168
 * @Date 2022/10/18 22:04
 */
public class CombinationSumSolution {
    public static void main(String[] args) {
        CombinationSumSolution solution = new CombinationSumSolution();
        int[] candidates = {2,3,6,7};
        int target = 7;
        List<List<Integer>> result = solution.combinationSum(candidates, target);
        result.forEach(System.out::println);
    }

    public List<List<Integer>> combinationSum(int[] candidates, int target) {
//        //给数组排序
//        Arrays.sort(candidates);
        List<List<Integer>> resultList = new ArrayList<>();

        int cdz = candidates.length;

        Deque<Integer> deque = new ArrayDeque<>();

        dfs(deque, 0,  cdz, candidates, target, resultList);

        return resultList;
    }

    public void dfs (Deque deque, int begin, int cdz, int[] candidates, int target, List<List<Integer>> resultList) {
        //如果target小于0或等于0，则处理后退出
        if (target < 0) {
            return;
        }
        if (target == 0) {
            resultList.add(new ArrayList<>(deque));
            return;
        }

        for (int i = begin; i < cdz; i++) {
            deque.addLast(candidates[i]);
            dfs(deque, i, cdz,candidates, target - candidates[i], resultList);
            //状态清除
            deque.removeLast();
        }
    }
}
